package com.myblog.shiro;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.myblog.common.lang.Result;
import com.myblog.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt:登录处理 jwt过期，不对 抛出异常
 *      正常：生产jwt凭证
 *    无jwt  其他权限控制交给注解处理
 * 定义jwt的过滤器JwtFilter
 * 继承的是Shiro内置的AuthenticatingFilter，
 * 一个可以内置了可以自动登录方法的的过滤器.
 */
@Component
public class JwtFilter extends AuthenticatingFilter {
    @Autowired
    JwtUtil jwtUtils;
    // JwtToken类继承了AuthenticationToken
    // 实现登录，需要生自定义支持的JwtToken
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        // 获取token
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        String jwt = request.getHeader("Authorization");
        if(StringUtils.isEmpty(jwt)){
            return null;
        }
        return new JwtToken(jwt);
    }

    /**
     * 实现拦截校验，当头部没有Authorization时候，直接通过，不需要登录
     * 当头部没有Authorization时候，首先我们校验jwt的有效性，
     * 没问题我们就直接执行executeLogin方法实现自动登录
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String jwt = request.getHeader("Authorization");

        if(StringUtils.isEmpty(jwt)){
            return true; // 放行
        }else{
            // 检验jwt 判断是否过期
            Claims claim = jwtUtils.getClaimByToken(jwt);
            if(claim==null || jwtUtils.isTokenExpired(claim.getExpiration())){
                throw new ExpiredCredentialsException("token已经失效，请重新登录!");
            }
        }

        return  executeLogin(servletRequest,servletResponse);
    }

    /**
     * 登录异常时候进入的方法，我们直接把异常信息封装然后抛出
     * @param token
     * @param e
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
                                    ServletRequest request,ServletResponse response ){
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        try{
            // 处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            Result r = Result.fail(throwable.getMessage()); // 填入失败信息
            String json = JSONUtil.toJsonStr(r);
            httpServletResponse.getWriter().print(json);

        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return false;
    }
    /**
     * 对跨域提供支持
     */
    /**
     * preHandle：拦截器的前置拦截，因为我们是前后端分析项目，
     * 项目中除了需要跨域全局配置之外，我们再拦截器中也需要提供跨域支持。
     * 这样，拦截器才不会在进入Controller之前就被限制了。
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request,ServletResponse response)throws Exception{
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin",httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个OPTIONS请求，这里要给OPTIONS 请求直接返回正常状态
        if(httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())){
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request,response);

    }
}
